package cn.akira.domain.strategy.service.rule.chain.impl;

import cn.akira.domain.strategy.repository.IStrategyRepository;
import cn.akira.domain.strategy.service.armory.IStrategyDispatch;
import cn.akira.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.akira.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.akira.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author fjl95
 * @date 2025/5/15
 * @description 权重规则校验链
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain{

    @Resource
    private IStrategyRepository strategyRepository;

    @Resource
    private IStrategyDispatch strategyDispatch;

    public Long userScore = 0L;
    @Override
    protected String ruleModel() {
        return "rule_weight";
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {

        //查到当前策略的rule_Weight_value
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleModel());
        //查到当前策略的rule_Weight_value的积分与奖品大映射map
        Map<Long,String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (analyticalValueGroup == null || analyticalValueGroup.isEmpty()) {
            return null;
        }
        //拿到阈值积分4000，5000,6000...
        List<Long> anallyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(anallyticalSortedKeys);

        //查询用户权重积分
        Integer userScore = strategyRepository.queryActivityAccountTotalUseCount(userId, strategyId);

        //找到当前积分所在的最小积分阈值
        Long nextValue = anallyticalSortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);
        if (null != nextValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId,String.valueOf(nextValue));
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        //传给下一个链
        return next().logic(userId, strategyId);
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }

}
